import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import(/* webpackChunkName: "home-chunk" */ '../pages/Home.vue'),
    meta: {
      name: 'slim',
      age: 18
    },
    children: [
      {
        path: 'category',
        component: () => import(/* webpackChunkName: "home-chunk" */ '../pages/HomeCategory.vue')
      }
    ]
  },
  {
    path: '/about',
    component: () => import(/* webpackChunkName: "home-chunk" */ '../pages/About.vue')
  },
  {
    path: '/post/:postId',
    component: () => import(/* webpackChunkName: "home-chunk" */ '../pages/Post.vue')
  },
  {
    path: '/profile',
    component: () => import(/* webpackChunkName: "home-chunk" */ '../pages/Profile.vue')
  },
  {
    path: '/login',
    component: () => import(/* webpackChunkName: "home-chunk" */ '../pages/Login.vue')
  },
  {
    // path: '/:pathMatch(.*)',
    path: '/:pathMatch(.*)*', // /abc/abc -> ['abc', 'abc']
    component: () => import(/* webpackChunkName: "home-chunk" */ '../pages/NotFound.vue')
  }
]

const router = createRouter({
  routes,
  history: createWebHistory()
})

// 动态添加路由
const route = {
  path: '/dynamicAdd',
  name: 'dynamicAdd',
  component: () => import(/* webpackChunkName: "home-chunk" */ '../pages/DynamicAddRoute.vue')
}
// 顶级路由
router.addRoute(route)
// 二级路由
const removeRoute = router.addRoute('dynamicAdd', {
  path: 'dynamicAdd2',
  component: () => import(/* webpackChunkName: "home-chunk" */ '../pages/DynamicAddRoute.vue')
})

// 删除路由
removeRoute()
router.removeRoute('dynamicAdd')

/**
 * 导航守卫 beforeEach
 * 
 * to: Route 对象，即将跳转到的 Route 对象
 * from: Route对象，跳转前的 Route 对象
 * 
 * 返回值：
 *    1.false: 不进行导航
 *    2.undefined或者不写返回值: 进行默认导航
 *    3.字符串: 路径, 跳转到对应的路径中
 *    4.对象: 类似于 router.push({path: "/login", query: ....})
 */
router.beforeEach((to, from) => {
  if (to.path !== '/login') {
    const token = window.localStorage.getItem('token')
    if (!token) {
      return '/login'
    }
  }
})

export default router
